package org.example.yolodemo.controller;

import org.example.yolodemo.util.OnnxLoadUtil;
import org.example.yolodemo.service.ImageDetectionService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.List;

@Controller
public class ImagesController {
    private static final String s = "C:\\Users\\HP\\IdeaProjects\\YoloDemo\\Image\\";

    private String filePath = "";
    
    private final ImageDetectionService detectionService;

    public ImagesController(ImageDetectionService detectionService) {
        this.detectionService = detectionService;
    }

    @RequestMapping("/toUpload")
    public String toUpload() {
        return "upload";
    }
    /**
     * 接收和保存图片
     * 文件上传的方式往往是POST
     * 图片传输方式以二进制字节流方式
     */
    @RequestMapping(value = "/uploadImage",method = RequestMethod.POST)
    @ResponseBody
    public void uploadImg(@RequestParam("file") MultipartFile file) throws IOException {
        byte[] bytes = file.getBytes();
        filePath= s+file.getOriginalFilename();
        //将图片进行写入到相关的文件夹当中去。
        Files.write(Paths.get(filePath), bytes);
    }

    @RequestMapping("/getImage")
    @ResponseBody
    public Map<String,String> getImage(@RequestParam("file") MultipartFile file) throws Exception {
        // 保存上传的图片
        byte[] bytes = file.getBytes();
        filePath = s + file.getOriginalFilename();
        Files.write(Paths.get(filePath), bytes);

        String modelPath = OnnxLoadUtil.getModelPath("models/best2.onnx");
        OnnxLoadUtil.load(modelPath);
        Map<Object,Object> map = OnnxLoadUtil.predict(filePath);
        System.out.println(filePath);
        OnnxLoadUtil.showDetect(map);
        
        // 保存检测结果到数据库
        if (map.get("boxes") == null) {
            throw new RuntimeException("No boxes detected in the image");
        }
        List<List<Float>> boxes = (List<List<Float>>) map.get("boxes");
        for (List<Float> box : boxes) {
            detectionService.saveDetectionResult(
                filePath.substring(filePath.lastIndexOf("\\") + 1),
                box.get(0),
                box.get(1),
                box.get(2),
                box.get(3)
            );
        }
        
        Map<String,String> map1 = new HashMap<>();
        map1.put("imagePath","/imgs/result.jpg");
        return map1;
    }
}
